package com.ning.farm_income_back.intercept;

import com.alibaba.fastjson.JSON;
import com.ning.farm_income_back.util.JwtUtils;
import com.ning.farm_income_back.vo.ResultVo;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class TokenIntercept implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //检查前端传过来的token
        response.setContentType("application/json;charset=UTF-8");
        String token = request.getHeader("token");
        if(!StringUtils.hasText(token)) {
            PrintWriter out = response.getWriter();
            out.write(JSON.toJSONString(ResultVo.reject("请先登录")));
            out.close();
            out.flush();
            return false;
        }
        try {
            JwtUtils.getUserName(token);
            return true;
        }catch (Exception e){
            PrintWriter out = response.getWriter();
            out.write(JSON.toJSONString(ResultVo.reject(e.getMessage())));
            out.close();
            out.flush();
            return false;
        }
    }
}
